﻿Imports System.Management
Imports Microsoft.ConfigurationManagement.ManagementProvider
Imports Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine
Imports System.Net

Public Class ConnectSmsProvider
    Public Shared Function Connect() As WqlConnectionManager
        Dim serverName As String = Nothing
        Dim userName As String = Nothing
        Dim userPassword As String = Nothing
        Dim smsProvider As String = Nothing
        Dim objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
        serverName = Getproviderlocation()
        Try
            Dim objSWbemServices = objSWbemLocator.ConnectServer(serverName, "root\sms", userName, userPassword)
            Dim providerLoc = objSWbemServices.InstancesOf("SMS_ProviderLocation")
            For Each Location In providerLoc
                If Location.ProviderForLocalSite = True Then
                    smsProvider = Location.Machine.ToString()
                End If
            Next
            Dim namedValues As New SmsNamedValuesDictionary()
            Dim connection As New WqlConnectionManager(namedValues)
            If Dns.GetHostName().ToUpper() = serverName.ToUpper() Then
                connection.Connect(smsProvider)
            Else
                connection.Connect(smsProvider, userName, userPassword)
            End If
            Return connection
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            Return Nothing
        End Try
    End Function
    Private Shared Function Getproviderlocation() As String
        Dim serverName As String = Nothing
        If NewUi.lblsmsproviderserver.Text = "Lazysmsprovider" Then
            Try
                Dim query As ManagementObjectSearcher
                query = New ManagementObjectSearcher("root\ccm", "Select * from SMS_Authority")
                For Each oReturn In query.Get
                    serverName = oReturn("CurrentManagementPoint").ToString()
                Next
            Catch ex As Exception
                serverName = InputBox("No SCCM Client detected, please Enter the SCCM Server Name")
                NewUi.lblsmsproviderserver.Text = serverName
            End Try
        Else
            serverName = NewUi.lblsmsproviderserver.Text
        End If
        Return serverName
    End Function
End Class
